package fr.gdi.android.news.importer;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;

import fr.gdi.android.news.FeedDescription;

public class LegacyFeedImporterTask extends AbstractFeedImporterTask
{
    public LegacyFeedImporterTask(Activity context, File file, Runnable callback)
    {
        super(context, file, callback);
    }
    

    @Override
    protected List<FeedDescription> getFeeds() throws Exception
    {
        final List<FeedDescription> feeds = new ArrayList<FeedDescription>();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader saxReader = parser.getXMLReader();
        saxReader.setContentHandler(new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
            {
                if ("feed".equals(localName))
                {
                    String name = attributes.getValue(attributes.getIndex("name"));
                    String url = attributes.getValue(attributes.getIndex("url"));
                    FeedDescription fd = new FeedDescription(name, url);
                    feeds.add(fd);
                }
            }
            
        });
        // saxReader.setErrorHandler(new DefaultHandler());
        saxReader.parse(new InputSource(new FileReader(file)));
            
        return feeds;
    }
}
